package cn.edu.zstu.qingzhu.qingzhushop.handler;

import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.util.HttpServletUtil;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-07-28 21:00
 */
@Component
public class CustomAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint
        implements AuthenticationEntryPoint {
    private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();

    public CustomAuthenticationEntryPoint() {
        super("/login");
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        MediaType acceptMediaType = HttpServletUtil.getRequestPrimaryAcceptMediaType(request);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authenticationTrustResolver.isAnonymous(authentication) || authenticationTrustResolver.isRememberMe(authentication)) {
            if (MediaType.TEXT_HTML.compareTo(acceptMediaType) == 0) {
                super.commence(request, response, authException);
                return;
            } else if (MediaType.APPLICATION_JSON.compareTo(acceptMediaType) == 0 || MediaType.ALL.compareTo(acceptMediaType) == 0) {
                response.setStatus(401);
                ResponseBean respBean = ResponseBean.error("访问失败!");
                if (authException instanceof InsufficientAuthenticationException) {
                    respBean.setMsg("请先登录!");
                }
                HttpServletUtil.writeObjectToResponse(response, respBean);
            }
        } else {
            response.setStatus(401);
            ResponseBean respBean = ResponseBean.error("访问失败!");
            if (authException instanceof InsufficientAuthenticationException) {
                respBean.setMsg("权限不足!");
            }
            HttpServletUtil.writeObjectToResponse(response, respBean);
        }
    }
}
